package com.hmall.api.config;

import com.hmall.api.client.fallback.ItemClientFallbackFactory;
import com.hmall.api.client.fallback.PayClientFallback;
import com.hmall.common.utils.UserContext;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;

/**
 * 本类中不是springMVC的配置类,没有加@Configuration注解
 * 所以里面的@Bean 不会被扫描到,所以不会被注册成bean
 * 所以需要在启动类中扫描本类
 * 也就是在需要调用Openfegin的启动类中添加@EnableFeignClients(value = "服务名" , defaultConfiguration = DefaultFeignConfig.class)
 */
public class DefaultFeignConfig {

    //实现每个服务之间的信息传递(将线程中保存的用户信息装入请求头中通过feign传递给其他服务)
    @Bean
    public RequestInterceptor userInfoRequestInterceptor() {
        return new RequestInterceptor() {
            public void apply(RequestTemplate requestTemplate) {
                Long userId = UserContext.getUser();
                if (userId != null) {
                    requestTemplate.header("user-info",userId.toString());
                }

            }
        };
    }

    //配置feign日志级别
    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }


    //将ItemClientFallbackFactory注册成一个bean
    //配置ItemClientFallbackFactory的fallback处理
    //最后得去ItemClient接口(也就是ItemCliemt这个openfegin)上添加@FeignClient(fallbackFactory = ItemClientFallbackFactory.class,让此配置生效)
    @Bean
    public ItemClientFallbackFactory itemClientFallbackFactory() {
        return new ItemClientFallbackFactory();
    }


    @Bean
    public PayClientFallback payClientFallbackFactory() {
        return new PayClientFallback();
    }
}
